import re

_BASE_REGEX_STRING = '^\s*%s\.%s\(\s*[\'"](.+)[\'"]\s*\)'
_GOOG_PROVIDE_REGEX = re.compile(_BASE_REGEX_STRING % ('goog', 'provide'))
_GOOG_REQUIRE_REGEX = re.compile(_BASE_REGEX_STRING % ('goog', 'require'))
_DOJO_PROVIDE_REGEX = re.compile(_BASE_REGEX_STRING % ('dojo', 'provide'))
_DOJO_REQUIRE_REGEX = re.compile(_BASE_REGEX_STRING % ('dojo', 'require'))

# This line identifies base.js and should match the line in that file.
_GOOG_BASE_LINE = (
    'var goog = goog || {}; // Identifies this file as the Closure base.')

def GetClosureDependencies(source):

  provides, requires = GetDependencies(source, _GOOG_PROVIDE_REGEX, _GOOG_REQUIRE_REGEX)

  # Closure's base file implicitly provides 'goog'.
  for line in source.splitlines():
    if line == _GOOG_BASE_LINE:
      if len(provides) or len(requires):
        raise Exception(
            'Base files should not provide or require namespaces.')
      provides.add('goog')

  return provides, requires

def GetDojoDependencies(source):
  return GetDependencies(source, _DOJO_PROVIDE_REGEX, _DOJO_REQUIRE_REGEX)

def GetDependencies(source, provides_re, requires_re):
  """Fill in provides and requires by scanning the source."""
  
  provides = set()
  requires = set()
  
  source_lines = source.splitlines()
  for line in source_lines:
    match = provides_re.match(line)
    if match:
      provides.add(match.group(1))

    match = requires_re.match(line)
    if match:
      requires.add(match.group(1))


  return provides, requires
